package jmotor.core.persistence.connection.impl;

import jmotor.core.persistence.connection.ConnectionManager;
import jmotor.core.persistence.exception.ConnectionException;
import jmotor.core.persistence.meta.ConnectionConfiguration;
import jmotor.util.ClassUtils;
import jmotor.util.StringUtils;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

/**
 * Component:
 * Description:
 * Date: 11-9-25
 *
 * @author Andy.Ai
 */
public class ConnectionManagerImpl implements ConnectionManager {

    public Connection connection(ConnectionConfiguration config) {
        try {
            if (StringUtils.isNotBlank(config.getServiceName())) {
                return getJndiConnection(config);
            }
            return getJdbcConnection(config);
        } catch (Exception e) {
            throw new ConnectionException("connection failure", e);
        }
    }

    private Connection getJdbcConnection(ConnectionConfiguration config) throws ClassNotFoundException, SQLException {
        ClassUtils.loadClass(config.getDriverClass());
        return DriverManager.getConnection(config.getUrl(), config.getUsername(), config.getPassword());
    }

    private Connection getJndiConnection(ConnectionConfiguration config) throws NamingException, SQLException {
        Context context = new InitialContext();
        DataSource dataSource = (DataSource) context.lookup(config.getServiceName());
        return dataSource.getConnection();
    }
}
